package com.hanshg.cherry.config.async;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 柠檬水
 */
@Configuration
@EnableAsync
public class AsyncConfig {

    private int corePoolSize = 10;
    private int maxPoolSize = 50;
    private int queueCapacity = 10;

    @Bean
    public Executor taskExecutor() {

        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        /**
         *设置核心线程数
         */
        executor.setCorePoolSize(corePoolSize);
        /**
         *设置最大线程数
         */
        executor.setMaxPoolSize(maxPoolSize);
        /**
         *线程池所使用的缓冲队列
         */
        executor.setQueueCapacity(queueCapacity);

        /**
         * 线程前缀
         */
        executor.setThreadNamePrefix("taskExecutor-");

        /**
         *  rejection-policy：当pool已经达到max size的时候，如何处理新任务
         *  CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        /**
         * 初始化
         */
        executor.initialize();
        return executor;
    }
}
